<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="70px">
                <el-form-item label="项目名">
                    <el-input v-model="search.projectName" placeholder="请输入项目名" clearable />
                </el-form-item>
                <el-form-item label="项目主体">
                    <el-select v-model="search.projectType" placeholder="请选择" clearable>
                        <el-option v-for="item, i in typeList" :key="i" :label="item.label" :value="item.label" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="项目时间">
                    <el-date-picker v-model="search.time" type="daterange" start-placeholder="开始时间" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" end-placeholder="结束时间" />
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="add-btn-box">
            <el-button type="primary" @click="handleaddProjectReport">新增</el-button>
            <div class="content-text">重点项目定义：合同金额500万以上及重点客户项目</div>
        </div>
        <el-table :data="rolesList" style="width: 100%;margin-top:16px;" border class="table-box" v-loading="loading"
            :height="height + 'px'">
            <el-table-column align="center" label="序号" width="60">
                <template slot-scope="scope">
                    {{ (pagination.pageNum - 1) * pagination.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="项目名" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.projectName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="项目主体" width="80">
                <template slot-scope="scope">
                    {{ scope.row.projectType }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="客户名称" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.customerName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="项目总体进展" v-element-table-tooltip>
                <template slot-scope="scope">
                    <span v-html="getTextToBr(scope.row.overallProgress)"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="本周进展" v-element-table-tooltip>
                <template slot-scope="scope">
                    <span v-html="getTextToBr(scope.row.weeklyProgress)"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="存在风险和问题" v-element-table-tooltip>
                <template slot-scope="scope">
                    <span v-html="getTextToBr(scope.row.currentProblem)"></span>
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="问题进展" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.problemProgress }}
                </template>
            </el-table-column> -->
            <el-table-column align="center" label="是否需要领导协调" width="80">
                <template slot-scope="scope">
                    {{ scope.row.coordinateFlag }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="当前阶段" width="80">
                <template slot-scope="scope">
                    {{ scope.row.currentStage }}
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="项目开始时间" width="110">
                <template slot-scope="scope">
                    {{ scope.row.projectBeginTime }}
                </template>
            </el-table-column> -->
            <el-table-column align="center" label="项目截止日期" width="110">
                <template slot-scope="scope">
                    {{ scope.row.projectEndTime }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="完成进度" width="80">
                <template slot-scope="scope">
                    {{ scope.row.finishProgress || 0 }}%
                </template>
            </el-table-column>
            <el-table-column align="center" label="时间进度" width="80">
                <template slot-scope="scope">
                    {{ scope.row.timeProgress ? truncateToFixed(scope.row.timeProgress, 1) : 0 }}%
                </template>
            </el-table-column>
            <el-table-column align="center" label="进展情况" width="80">
                <template slot-scope="scope">
                    <span :style="{ color: getColor(scope.row.taskImplementation) }"> {{ scope.row.taskImplementation}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="140">
                <template slot-scope="scope">
                    <el-button type="text" @click="goDetail(scope)">详情</el-button>
                    <el-button type="text" @click="handleEdit(scope)">编辑</el-button>
                    <el-button type="text" @click="handleDelete(scope)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize"
            @pagination="getPagination" />
        <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : '新增'" top="7vh" width="1300px"
            :close-on-click-modal="false">
            <el-form :model="role" label-width="140px" label-position="right" :rules="rules" ref="ruleForm">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="项目名" prop="projectName">
                            <el-input v-model="role.projectName" placeholder="请输入项目名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目主体" prop="projectType">
                            <el-select v-model="role.projectType" placeholder="请选择" clearable>
                                <el-option v-for="item, i in typeList" :key="i" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="khmc">
                            <el-input v-model="role.customerName" placeholder="请输入客户名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否需要领导协调" prop="coordinateFlag">
                            <el-select v-model="role.coordinateFlag" placeholder="请选择" clearable>
                                <el-option label="是" value="是"></el-option>
                                <el-option label="否" value="否"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="当前阶段" prop="currentStage">
                            <el-select v-model="role.currentStage" placeholder="请选择" clearable>
                                <el-option v-for="item, i in projectPhase" :key="i" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目时间" prop="projectBeginTime">
                            <!-- <el-date-picker v-model="role.projectBeginTime" type="date" placeholder="选择日期"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd" />  -->
                            <el-date-picker v-model="role.time" type="daterange" value-format="yyyy-MM-dd"
                                start-placeholder="项目开始日期" end-placeholder="项目截止日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="完成进度(%)">
                            <el-input-number v-model="role.finishProgress" placeholder="请输入完成进度"
                                controls-position="right" :min="0" :max="100" :precision="0" :step="1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户负责人" prop="customerMgr">
                            <el-input v-model="role.customerMgr" placeholder="请输入客户负责人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户经理" prop="accountManager">
                            <el-input v-model="role.accountManager" placeholder="请输入客户经理" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品责任人" prop="productMgr">
                            <el-input v-model="role.productMgr" placeholder="请输入产品责任人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="交付经理" prop="deliveryMgr">
                            <el-input v-model="role.deliveryMgr" placeholder="请输入交付经理" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合作伙伴" prop="partnerName">
                            <el-input v-model="role.partnerName" placeholder="请输入合作伙伴" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="后向合同金额(万元)" prop="afterContractAmount">
                            <el-input-number v-model="role.afterContractAmount" controls-position="right" placeholder="请输入后向合同金额(万元)" :min="0"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="付款金额(万元)" prop="payAmount">
                            <el-input-number v-model="role.payAmount" controls-position="right" placeholder="请输入付款金额(万元)" :min="0"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="下游厂家" prop="companyName">
                            <el-input v-model="role.companyName" placeholder="请输入下游厂家" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="项目总体进展" prop="overallProgress">
                            <el-input v-model="role.overallProgress" placeholder="请输入项目总体进展" type="textarea"
                                :autosize="{ minRows: 1, maxRows: 3 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="本周进展" prop="weeklyProgress">
                            <el-input v-model="role.weeklyProgress" placeholder="请输入本周进展" type="textarea"
                                :autosize="{ minRows: 1, maxRows: 3 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="存在风险和问题" prop="currentProblem">
                            <el-input v-model="role.currentProblem" placeholder="请输入当前存在问题、存在风险及风险是否可控" type="textarea"
                                :autosize="{ minRows: 1, maxRows: 3 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="后向合同进展" prop="afterContractProgress">
                            <el-input v-model="role.afterContractProgress" placeholder="请输入后向合同进展"  type="textarea"  :autosize="{ minRows: 1, maxRows: 3 }" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="text-align:right;">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRole">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { selectProjectReport, addProjectReport, deleteProjectReport, updateProjectReport } from '@/api/api'
import Pagination from '@/components/Pagination'
import addDialog from './components/addDialog.vue'
const defaultRole = { time: [] }

export default {
    name: 'work',
    components: { Pagination, addDialog },
    data() {
        return {
            projectPhase: projectPhase,
            typeList: projectType,
            rules: {
                projectName: [
                    { required: true, message: '请输入项目名', trigger: 'change' }
                ],
                projectType: [
                    { required: true, message: '请选择项目主体', trigger: 'change' }
                ],
            },
            loading: false,
            height: 400,
            total: 0,
            role: Object.assign({}, defaultRole),
            routes: [],
            rolesList: [],
            dialogVisible: false,
            dialogType: 'new',
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            search: { executor: '' },
            pfOptions: [],
            zxOptions: [],
            pagination: {
                'pageNum': 1,
                'pageSize': 20
            },
            time: null,
        }
    },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.role = { time: [] }
                this.$refs['ruleForm'].resetFields();
            }
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (to.path == '/work/list') {
                vm.onSubmit();
            }
        });
    },
    computed: {
        routesData() {
            return this.routes
        }
    },
    created() {
        this.getTasks();
        this.height = this.getHeight();
        let that = this;
        window.onresize = function (event) {
            that.height = that.getHeight();
        };
    },
    methods: {
        getTextToBr(text) {
            return text ? text.replace(/\n/g, '<br />') : '--'
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value || 0); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        getHeight() {
            let winHieght = window.innerHeight;
            return winHieght - 280;
        },
        onSubmit() {
            this.pagination = {
                "pageNum": 1,
                "pageSize": 20
            }
            this.getTasks()
        },
        reset() {
            this.search = {}
            this.onSubmit()
        },
        getPagination(pagination) {
            this.pagination = pagination
            this.getTasks()
        },
        getColor(finishState) {
            const colors = {
                '超前': '#1ecd00',
                '正常': '#1ecd00',
                '已完成': '#1ecd00',
                '进行中': '#1890ff',
                '待开始': '#999',
                '已延期': '#ff4949',
                '落后': '#ff4949'
            }
            return colors[finishState]
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value || 0); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        goDetail(scope) {
            this.$router.push({
                path: `/weeklyReport/ganttDetail/${scope.row.keyId}`
            })
        },
        async getTasks() {
            try {
                this.loading = true
                const res = await selectProjectReport({ page: this.pagination.pageNum, size: this.pagination.pageSize, ...this.search, distributor: localStorage.getItem('userName'), taskType: '20' });
                this.total = res.total || 0;
                this.rolesList = res?.list || [];
                this.loading = false
            } catch (error) {
                this.loading = false
            }
        },
        handleaddProjectReport() {
            this.role = Object.assign({}, defaultRole)
            if (this.$refs.tree) {
                this.$refs.tree.setCheckedNodes([])
            }
            this.dialogType = 'new'
            this.dialogVisible = true
        },
        async handleEdit(scope) {
            await this.getEdit(scope)
        },
        getEdit(scope) {
            let time = scope.row.projectBeginTime ? [scope.row.projectBeginTime, scope.row.projectEndTime] : []
            this.role = { ...scope.row, time }
            this.dialogType = 'edit'
            this.dialogVisible = true
        },
        handleDelete({ $index, row }) {
            this.$confirm(`确认删除“${row.projectName}”的项目数据?`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    deleteProjectReport(row.keyId).then(res => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                            this.getTasks();
                        } else {
                            this.$message({
                                type: 'warning',
                                message: res.message
                            })
                            this.getTasks();
                        }
                    })
                })
                .catch(err => { console.error(err) })
        },
        confirmRole() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === 'edit'
                    let params = {
                        ...this.role,
                        projectBeginTime: this.role.time && this.role.time.length ? this.role.time[0] : '',
                        projectEndTime: this.role.time && this.role.time.length ? this.role.time[1] : '',
                        finishProgress: this.role.finishProgress ? this.role.finishProgress : 0
                    }
                    if (isEdit) {
                        updateProjectReport({ ...params }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                        })
                    } else {
                        addProjectReport({ ...params }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    height: 37px;
}
.app-container {
    overflow-y: auto;
    height: calc(100vh - 86px);
    padding: 16px 20px 0;

    .roles-table {
        margin-top: 30px;
    }

    .permission-tree {
        margin-bottom: 30px;
    }
}


.filter-container {
    ::v-deep .el-form-item {
        margin-bottom: 0;
    }
}

::v-deep .el-select,
::v-deep .el-date-editor.el-input,
::v-deep .el-date-editor.el-input__inner {
    width: 100%;
}

.table-box {
    ::v-deep .el-button--medium {
        padding: 0px 5px;
    }
}

.popover-list {
    min-height: 30px;
    line-height: 30px;
    cursor: pointer;
    padding: 0 10px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;

    &:hover {
        background: #f3f6fb;
    }
}

.all-num-box {
    margin-left: 20px;

    .green {
        color: #1ecd00;
        margin: 0 2px;
    }

    .blue {
        color: #1890ff;
        margin: 0 2px;
    }
}

::v-deep .el-date-editor--daterange.el-input__inner {
    width: 100%;
}

::v-deep .table-box .el-button--medium {
    padding: 0;
}

::v-deep .el-input-number--medium {
    width: 100%;
}

::v-deep .el-input-number.is-controls-right .el-input__inner {
    text-align: left;
}

.add-btn-box {
    position: relative;
}

.content-text {
    color: #0558c3;
    margin-left: 10px;
    font-size: 18px;
    font-family: 仿宋;
    position: absolute;
    font-weight: bold;
    top: 9px;
    left: 80px;
}
</style>
<style>
.popper-list {
    padding: 0;
}

.popperClass {
    width: 500px;
}
</style>